//
//  MYStatusListViewModel.swift
//  swift2.0项目开始
//
//  Created by 龚昕炜 on 16/8/1.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

class MYStatusListViewModel: NSObject {
    
    /** 模型数组 */
    lazy var list: [MYHomeCellViewModel] = [MYHomeCellViewModel]()
    
    /** 加载数据 */
    func loadData(since_id: Int = 0, max_id: Int = 0, success: ()->(), failed: ()->()) {
    
        let URLString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let token = MYLoginViewModel.shareInstance.access_token else {
            return
        }
        
        let params = ["access_token": token,
                      "since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        MYHTTPClient.shareInstance.request(.GET, URLString: URLString, parameters: params, progress: nil, success: { (_, JSON) -> Void in
            
            /** 处理JSON */
            guard let json = JSON as? [String: AnyObject] else {
                return
            }
            
            /** 初始化一个数组 */
            var temp: [MYHomeCellViewModel] = [MYHomeCellViewModel]()
            
            /** 调度组 */
            let group = dispatch_group_create()
            
            if let statuses = json["statuses"] as? [[String: AnyObject]] {
                
                for status in statuses {
                    
                    let statusModel = MYStatusModel(dict: status)
                    
                    /** 如果转发微博有图 */
                    let pic_urls = (statusModel.pic_urls == nil) ? statusModel.retweeted_status?.pic_urls : statusModel.pic_urls
                    /** 如果为单张图片(注意此处不能用guard,因为若是count不为1就返回会导致count == 1的也无法执行) */
                    if let pic_URLS = pic_urls where pic_urls!.count == 1 {
                        
                    /** URL */
                        guard let urlString = pic_URLS.first?.thumbnail_pic else {
                            return
                        }
                        let URL = NSURL(string: urlString)
                    
                    /** 进入组 */
                        dispatch_group_enter(group)
                    /** 下载图片 */
                        SDWebImageManager.sharedManager().downloadImageWithURL(URL, options: [], progress: nil, completed: { (iamge, error, _, _, _) -> Void in
                            if error != nil {
                                print(error)
                            } else {
                                print("图片下载完成")
                            }
                            dispatch_group_leave(group)
                        })
                }
                
                    let viewModel = MYHomeCellViewModel()
                    
                    viewModel.statusModel = statusModel
                    
                    temp.append(viewModel)
                }
                if since_id > 0 {
                    /** 赋值 */
                    self.list = temp + self.list
                } else {
                    self.list = self.list + temp
                }
            }
            
            /** 图片下载完成才回调 */
            dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
                success()
            })
            }) { (_, error) -> Void in
                print(error)
                failed()
        }
    }
    
    
    
}
